package com.zhansm.filesys.controller;
import com.zhansm.filesys.entity.FileEntity;
import com.zhansm.filesys.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    FileService fileService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadElementFile( @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException{
        if(file.isEmpty()){
            return ResponseEntity.notFound().build();
        }
        String fileName = fileService.uploadFile(file.getBytes(),file.getOriginalFilename());

        return ResponseEntity.ok(fileName);
    }

    @GetMapping("/download/{fileName}")
    public ResponseEntity<String> download(@PathVariable("fileName") String fileName, HttpServletResponse response){
        try {
            fileService.downloadFile(fileName,response);
            return ResponseEntity.ok().build();
        }catch (Exception e){
            return ResponseEntity.status(410).build();
        }
    }

    @GetMapping("/getData/{fileName}")
    public ResponseEntity<FileEntity> getData(@PathVariable("fileName") String fileName){
            FileEntity fileEntity =  fileService.get(fileName);
            if (fileEntity!=null){
                return ResponseEntity.ok(fileEntity);
            }else {
                return ResponseEntity.notFound().build();
            }
    }
}
